package com.doctor.windflower_doctor.adapter;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.actionBeen.QuestionAction;
import com.doctor.windflower_doctor.activity.QuestionOnLineActivity;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.entity.QuestionBeen;
import com.doctor.windflower_doctor.http.callback.HttpRequestCallBack;
import com.doctor.windflower_doctor.http.parser.impl.JsonParser;
import com.doctor.windflower_doctor.http.request.HttpRequest;
import com.doctor.windflower_doctor.http.request.HttpRequestParams;
import com.doctor.windflower_doctor.http.response.HttpResponseInfo;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.util.LogUtils;
import com.doctor.windflower_doctor.util.StringUtil;
import com.doctor.windflower_doctor.util.TimerManager;
import com.doctor.windflower_doctor.view.LoadingDialog;
import com.doctor.windflower_doctor.view.RoundedImageView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * <p>
 * 功能
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年10月30日 下午4:42:39
 * @version 1.0 </br> 最后修改人 无
 * 
 */
public class QuestionStateAdapter extends BaseAdapter implements Constent {
	private Context context;
	private LayoutInflater inflater;
	private List<QuestionBeen> questionBeens;
	private DisplayImageOptions options;
	private int replyStatus = 0;
	private LoadingDialog loadingDialog;
	private String userId;
	private String questionId;
	private String name;
	private ListView toBeSolvedList;
	private TimerManager timerManager;
	private String keyword = "";

	public QuestionStateAdapter(Context context, int replyStatus) {
		this.context = context;
		this.replyStatus = replyStatus;
		this.inflater = LayoutInflater.from(context);
		this.questionBeens = new ArrayList<QuestionBeen>();
		options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.loading_img).showImageOnFail(R.drawable.loading_img)
				.showImageForEmptyUri(R.drawable.loading_img).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.ARGB_8888).build();
		this.loadingDialog = new LoadingDialog((Activity) context);
		timerManager = TimerManager.getInstance();
		timerManager.setHandler(mHandler);
	}

	public void setListView(ListView toBeSolvedList) {
		this.toBeSolvedList = toBeSolvedList;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return questionBeens.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return questionBeens.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {
		// TODO Auto-generated method stub
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.item_my_question_state, arg2, false);
			holder.user_icon = (RoundedImageView) convertView.findViewById(R.id.user_icon);
			holder.replay_num = (TextView) convertView.findViewById(R.id.replay_num);
			holder.tv_nick = (TextView) convertView.findViewById(R.id.tv_nick);
			holder.tv_age = (TextView) convertView.findViewById(R.id.tv_age);
			holder.tv_month = (TextView) convertView.findViewById(R.id.tv_month);
			holder.timer_text = (TextView) convertView.findViewById(R.id.timer_text);
			holder.tv_rob = (TextView) convertView.findViewById(R.id.tv_rob);
			holder.problem_content = (TextView) convertView.findViewById(R.id.problem_content);
			holder.problem_type = (TextView) convertView.findViewById(R.id.problem_type);
			holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
			holder.rob = (ImageView) convertView.findViewById(R.id.rob);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.replay_num.setVisibility(View.GONE);
		holder.rob.setVisibility(View.GONE);
		holder.timer_text.setVisibility(View.GONE);
		final QuestionBeen questionBeen = questionBeens.get(position);
		questionBeen.index = position;
		SystemApplication.getInstance().mImageLoad1.displayImage(questionBeen.imgUrl, holder.user_icon, options);
		if (!StringUtil.isEmpty(questionBeen.numberOfReply) && Integer.parseInt(questionBeen.numberOfReply) > 0) {
			holder.replay_num.setText(questionBeen.numberOfReply);
			holder.replay_num.setVisibility(View.VISIBLE);
		}
		holder.tv_nick.setText(!(StringUtil.isEmpty(questionBeen.name)) ? questionBeen.name : !(StringUtil.isEmpty(questionBeen.nick)) ? questionBeen.nick
				: "用户" + questionBeen.id.subSequence(questionBeen.id.length() - 6, questionBeen.id.length()));
		if (!StringUtil.isEmpty(questionBeen.age + ""))
			holder.tv_age.setText(questionBeen.age + "岁");
		holder.tv_month.setText(questionBeen.prePeriod);
		holder.problem_content.setText(questionBeen.text);

		if (!StringUtil.isEmpty(keyword) && questionBeen.text.contains(keyword)) {
			int index = 0;
			SpannableStringBuilder builder = new SpannableStringBuilder(holder.problem_content.getText().toString());
			while (holder.problem_content.getText().toString().indexOf(keyword, index) >= 0) {
				int start = holder.problem_content.getText().toString().indexOf(keyword, index);
				ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.parseColor("#eeb461"));
				builder.setSpan(yellowSpan, start, start + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				index = (start + keyword.length());
			}
			holder.problem_content.setText(builder);
		}
		holder.problem_type.setText(questionBeen.classification);
		holder.tv_time.setText(questionBeen.createTime);
		switch (replyStatus) {
		case 0:
			holder.tv_rob.setText("抢答");
			break;
		case 1:
			if (SystemApplication.getInstance().replyStatus == 1 && replyStatus != 1) {
				timerManager.stopTimer();
			}
			if (questionBeen.isAnswer) {
				holder.rob.setVisibility(View.VISIBLE);
				holder.timer_text.setVisibility(View.VISIBLE);
				holder.timer_text.setText(context.getResources().getString(R.string.timer) + cal(questionBeen.restOfTime));
				SpannableStringBuilder builder = new SpannableStringBuilder(holder.timer_text.getText().toString());
				ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
				builder.setSpan(redSpan, 9, holder.timer_text.getText().toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				holder.timer_text.setText(builder);
				questionBeen.timeCurrentLimit = questionBeen.restOfTime;
				// LogUtils.e("=====getView=====startTimer==" +
				// "===========holder==========" + holder);
				timerManager.startTimer(questionBeen);
			}
			holder.tv_rob.setText("回答");
			break;
		case 2:
			holder.tv_rob.setText("回答");
			break;
		case 3:
			holder.tv_rob.setText("查看");
			break;
		}

		holder.tv_rob.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View argw) {
				userId = questionBeen.userId;
				questionId = questionBeen.questionId;
				name = !(StringUtil.isEmpty(questionBeen.name)) ? questionBeen.name : questionBeen.nick;
				if (replyStatus == 1) {
					post();
				} else {
					timerManager.stopTimer();
					Intent intent = new Intent(context, QuestionOnLineActivity.class);
					Bundle bundle = new Bundle();
					bundle.putInt("replyStatus", replyStatus);
					bundle.putString(QUESTIONID, questionId);
					bundle.putString(USERID, userId);
					bundle.putString(NAME, name);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
			}
		});
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				userId = questionBeen.userId;
				questionId = questionBeen.questionId;
				name = !(StringUtil.isEmpty(questionBeen.name)) ? questionBeen.name : questionBeen.nick;
				if (replyStatus == 1) {
					post();
				} else {
					timerManager.stopTimer();
					Intent intent = new Intent(context, QuestionOnLineActivity.class);
					Bundle bundle = new Bundle();
					bundle.putInt("replyStatus", replyStatus);
					bundle.putString(QUESTIONID, questionId);
					bundle.putString(USERID, userId);
					bundle.putString(NAME, name);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
			}
		});
		return convertView;
	}

	public void addListData(List<QuestionBeen> questionBeens) {
		if (questionBeens != null) {
			this.questionBeens.addAll(questionBeens);
			notifyDataSetChanged();
		}
	}

	public void clearData() {
		if (questionBeens != null) {
			timerManager.stopTimer();
			this.questionBeens.clear();
			notifyDataSetChanged();
		}
	}

	class ViewHolder {
		RoundedImageView user_icon;
		TextView replay_num;
		TextView tv_nick;
		TextView tv_age;
		TextView tv_month;
		TextView timer_text;
		TextView tv_rob;
		TextView problem_content;
		TextView problem_type;
		TextView tv_time;
		ImageView rob;
	}

	/**
	 * <p>
	 * 功能 进入详情判断是否能够回复
	 * </p>
	 * 
	 * @author 皮勉 时间 2014年11月6日 下午1:09:25
	 */
	void post() {
		HttpMethod requestMethod = HttpMethod.GET;
		String requestUrl = URL + ASK_DOCTOR_ISALLOWED + "?" + DOCTORID + "=" + SharedPreferencesDB.getInstance(context).getDocotorId() + "&" + QUESTIONID
				+ "=" + questionId;
		LogUtils.e("requestUrl>>>>>>>>>" + requestUrl);
		HttpRequestCallBack<QuestionAction> requestCallBack = new HttpRequestCallBack<QuestionAction>(new JsonParser(), QuestionAction.class) {
			@Override
			protected void handleResult(HttpResponseInfo<QuestionAction> responseInfo) {
				loadingDialog.close();
				if (responseInfo.success.success) {
					timerManager.stopTimer();
					Intent intent = new Intent(context, QuestionOnLineActivity.class);
					Bundle bundle = new Bundle();
					bundle.putInt("replyStatus", replyStatus);
					bundle.putString(QUESTIONID, questionId);
					bundle.putString(USERID, userId);
					bundle.putString(NAME, name);
					intent.putExtras(bundle);
					context.startActivity(intent);
				}
			}

			@Override
			protected void handleError(HttpException e, String msg) {
				loadingDialog.close();
				LogUtils.e("=====getUserInfermation====3===" + msg);
			}

			@Override
			public void onStart() {
				loadingDialog.show();
				super.onStart();

			}
		};
		HttpRequestParams params = new HttpRequestParams(requestMethod, requestUrl, requestCallBack);
		HttpRequest.send(params);
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			QuestionBeen questionBeen = (QuestionBeen) msg.obj;
			// LogUtils.e("=====replyStatus=======" +
			// SystemApplication.getInstance().replyStatus);
			if (SystemApplication.getInstance().replyStatus == 1 && questionBeens.size() >= questionBeen.index) {
				questionBeens.get(questionBeen.index).timeCurrentLimit = questionBeen.timeCurrentLimit;
				// LogUtils.e("=====updateView=======" + questionBeen.index);
				updateView(questionBeen.index);
			} else {
				timerManager.stopTimer();
				questionBeens.remove(questionBeen);
				notifyDataSetChanged();
			}
			super.handleMessage(msg);

		}
	};

	// 更新指定item的数据
	private void updateView(int index) {
		final QuestionBeen questionBeen = questionBeens.get(index);
		// int visiblePos = toBeSolvedList.getFirstVisiblePosition();

		int firstVisiblePosition = toBeSolvedList.getFirstVisiblePosition();
		int lastVisiblePosition = toBeSolvedList.getLastVisiblePosition();

		int offset = index - firstVisiblePosition;
		// Log.e("", "index="+index+"visiblePos="+visiblePos+"offset="+offset);
		// 只有在可见区域才更新
		if (offset < 0) {
			// LogUtils.e("===============offset========<0======" + offset);
			return;
		}
		if (index >= firstVisiblePosition && index <= lastVisiblePosition) {
			// LogUtils.e("===============offset==============" + offset);
			View view = toBeSolvedList.getChildAt(offset);
			ViewHolder holder = (ViewHolder) view.getTag();
			// Log.e("", "id="+app.id+", name="+app.name);
			// LogUtils.e("=====timeState=======" + questionBeen.timeState +
			// "=======holder=========" + holder);
			if (questionBeen.timeState != 1) {
				holder.timer_text.setText(context.getResources().getString(R.string.timer) + cal(questionBeen.timeCurrentLimit));
				SpannableStringBuilder builder = new SpannableStringBuilder(holder.timer_text.getText().toString());
				ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
				builder.setSpan(redSpan, 9, holder.timer_text.getText().toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				holder.timer_text.setText(builder);
			} else {
				holder.timer_text.setVisibility(View.GONE);
			}

		}
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public static String cal(int second) {
		int h = 0;
		int d = 0;
		int s = 0;
		int temp = second % 3600;
		if (second > 3600) {
			h = second / 3600;
			if (temp != 0) {
				if (temp > 60) {
					d = temp / 60;
					if (temp % 60 != 0) {
						s = temp % 60;
					}
				} else {
					s = temp;
				}
			}
		} else {
			d = second / 60;
			if (second % 60 != 0) {
				s = second % 60;
			}
		}

		return h + ":" + d + ":" + s;
	}

}
